#Python's anonymous functions
Anonymous functions let you quickly create simple functions without defining a full function using the def
keyword. In Python, anonymous functions are created with the lambda
keyword:
lambda parameter_list : return_value
For example:
names: list[str] = ['Tuffy', 'Spike', 'Tom', 'Jerry']
names.sort(key=lambda x: len(x)) # Sort by length
print(names)
#First-Class Functions
In Python, functions are first-class values, meaning you can assign them directly to variables:
# Define a function
def func(x: str):
return len(x)
# Assign function to a variable
variable = func
# Call function through the variable
print(variable('hello'))
# Simplify with lambda
variable = lambda x: len(x)
# Call function through the variable
print(variable('world'))